package com.zr.customtagview;


import java.util.ArrayList;
import java.util.List;



import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

@SuppressLint("NewApi") 
public class CustomTagView extends LinearLayout{

	private LinearLayout mRootLayout;
	
	private OnOverMaxNumberCheckListener mOverMaxNumberCheckListener;
	
	/**
	 * System Service
	 */
	private LayoutInflater mInflater;
	private ViewTreeObserver mViewTreeObserber;
	/**
	 * layout initialize flag
	 */
	private boolean mInitialized = false;

	/** 屏幕宽度 */
	private int mScreenWidth;
	
	/** 默认每行标签距离 */
	private int DEFAULT_LINE_PADDING = 20;
	/** 默认同行标签之间距离 */
	private int DEFAULT_TAG_PADDING = 10;
	/** 默认同行标签之间距离 */
	private int DEFAULT_TAG_HEIGHT = 90;
	/** 默认标签到屏幕边的距离 */
	private int DEFAULT_TAG_MARGIN_EDAGE = 20;
	/** 默认标签列数 */
	private int DEFAULT_TAG_COLUMNS = 3;
	/** 默认标签是否可选中，默认true */
	private boolean DEFAULT_TAG_CHECKABLE = true;
	/** 默认标签列数 */
	private int DEFAULT_TAG_MAXCHECKNUMBER = 3;
	
	
	/** 标签宽度 */
	int tagWidth;
	/** 标签高度 */
	int tagHeight;
	/** 标签的列数设置，默认为3个 */
	int columns;
	/** 每行标签的距离 */
	int linePadding;
	/** 同一行标签之间的距离 */
	int tagPadding;
	/** 标签到屏幕边的距离 */
	int tagMaeginEdage;
	/** 标签是否可选中 */
	boolean checkable;
	/** 标签可选择的个数,默认3个可选中 */
	int  maxCheckNumber;
	
	private List<TagInfo> tags;
	
	private int[] normalImageIds = {
			R.drawable.tag_normal_1,
			R.drawable.tag_normal_2,
			R.drawable.tag_normal_3,
			R.drawable.tag_normal_4,
			R.drawable.tag_normal_5,
			R.drawable.tag_normal_6,
			R.drawable.tag_normal_7,
			R.drawable.tag_normal_8,
			R.drawable.tag_normal_9,
			R.drawable.tag_normal_10,
			R.drawable.tag_normal_11,
			R.drawable.tag_normal_12,
	};
	
	private int[] checkedImageIds = {
			R.drawable.tag_checked_1,
			R.drawable.tag_checked_2,
			R.drawable.tag_checked_3,
			R.drawable.tag_checked_4,
			R.drawable.tag_checked_5,
			R.drawable.tag_checked_6,
			R.drawable.tag_checked_7,
			R.drawable.tag_checked_8,
			R.drawable.tag_checked_9,
			R.drawable.tag_checked_10,
			R.drawable.tag_checked_11,
			R.drawable.tag_checked_12,
	};

	public void setTags(List<TagInfo> tags) {
		this.tags = tags;
	}

	/**
	 * 获取每行标签得距离
	 * @return
	 */
	public int getLinePadding() {
		return linePadding;
	}

	/**
	 * 设置每行标签得距离
	 * @return
	 */
	public void setLinePadding(int linePadding) {
		this.linePadding = Utils.dipToPx(getContext(), linePadding);
	}

	public int getTagPadding() {
		return tagPadding;
	}

	/**
	 * 设置同一行标签之间得距离
	 * @param tagPadding
	 */
	public void setTagPadding(int tagPadding) {
		this.tagPadding = Utils.dipToPx(getContext(), tagPadding);
	}

	public int getTagMaeginEdage() {
		return tagMaeginEdage;
	}

	/**
	 * 设置标签到屏幕得距离
	 * @param tagMaeginEdage
	 */
	public void setTagMaeginEdage(int tagMaeginEdage) {
		this.tagMaeginEdage = Utils.dipToPx(getContext(), tagMaeginEdage);
	}

	public int getTagHeight() {
		return tagHeight;
	}
	
	/**
	 * 设置标签tag的高度
	 * @param mTagHeight
	 */
	public void setTagHeight(int tagHeight) {
		this.tagHeight = Utils.dipToPx(getContext(), tagHeight);
	}

	public int getColumns() {
		return columns;
	}

	/**
	 * 设置标签的列数
	 * @param columns
	 */
	public void setColumns(int columns) {
		this.columns = columns;
	}
	
	

	/**
	 * 获取选中标识位
	 * @return
	 */
	public boolean isCheckable() {
		return checkable;
	}

	/**
	 * 设置是否可选中标志位
	 * @param checkable
	 */
	public void setCheckable(boolean checkable) {
		this.checkable = checkable;
	}
	
	

	public int getMaxCheckNumber() {
		return maxCheckNumber;
	}

	/**
	 * 设置最大的可选择个数，默认为3
	 * @param maxCheckNumber
	 */
	public void setMaxCheckNumber(int maxCheckNumber) {
		this.maxCheckNumber = maxCheckNumber;
	}

	public CustomTagView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, attrs, defStyle);
	}

	public CustomTagView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs, 0);
	}

	public CustomTagView(Context context) {
		super(context);
		init(context, null, 0);
	}

	private void init(final Context context, AttributeSet attrs, int defStyle) {
		tags = new ArrayList<TagInfo>();
		
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mViewTreeObserber = getViewTreeObserver();
		mViewTreeObserber.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				if (!mInitialized) {
					mInitialized = true;
					createView(context);
				}
			}
		});
		
		// get AttributeSet
		TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTagView, defStyle, defStyle);
		this.linePadding =(int) typeArray.getDimension(R.styleable.CustomTagView_linePadding, Utils.dipToPx(context, DEFAULT_LINE_PADDING));
		this.tagPadding =(int) typeArray.getDimension(R.styleable.CustomTagView_tagPadding,Utils.dipToPx(context, DEFAULT_TAG_PADDING));
		this.columns =(int) typeArray.getInt(R.styleable.CustomTagView_columns, DEFAULT_TAG_COLUMNS);
		this.tagHeight =(int) typeArray.getDimension(R.styleable.CustomTagView_tagHeight, Utils.dipToPx(context, DEFAULT_TAG_HEIGHT));
		this.tagMaeginEdage =(int) typeArray.getDimension(R.styleable.CustomTagView_tagMaeginEdage, Utils.dipToPx(context, DEFAULT_TAG_MARGIN_EDAGE));
		this.checkable =(boolean) typeArray.getBoolean(R.styleable.CustomTagView_checkable, DEFAULT_TAG_CHECKABLE);
		this.maxCheckNumber =(int) typeArray.getInt(R.styleable.CustomTagView_maxCheckNumber, DEFAULT_TAG_MAXCHECKNUMBER);
		typeArray.recycle();
	}

	/**
	 * 生成标签的自定义view
	 * @param context
	 */
	public void createView(Context context) {
		if (!mInitialized) {
			return;
		}
		int index = -1;
		mInflater.inflate(R.layout.custom_tag_layout, this, true);
		mRootLayout = (LinearLayout) findViewById(R.id.rootview);
		//获取当前屏幕宽度
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		mScreenWidth = wm.getDefaultDisplay().getWidth();
		tagWidth = (mScreenWidth - 2 * tagMaeginEdage - (columns-1) * tagPadding) / columns;
		
		for (int i = 1; i <= (tags.size()/columns + 1); i++) {
			LinearLayout layout = new LinearLayout(context);
			layout.setOrientation(LinearLayout.HORIZONTAL);
			layout.setLayoutParams(new LayoutParams(mScreenWidth - 2 * tagMaeginEdage, tagHeight + linePadding));
			LayoutParams params = new LinearLayout.LayoutParams(tagWidth, tagHeight);
			for (int j = 1; j <= columns; j++) {
				++index;
				if(index >= tags.size()){
					break;
				}
				TextView tv = new TextView(context);
				if(isCheckable()){
					tv.setClickable(true);
					tv.setOnClickListener(myTagCheckListener);
				}
				tv.setTextSize(12);
				tv.setGravity(Gravity.CENTER_VERTICAL);
				tv.setText(tags.get(index).getContent());
				tags.get(index).setIndex(index);
				tv.setTag(tags.get(index));
				showTagNormal(context, tv);
				layout.addView(tv, params);
				if(j != columns){   //不是最后一列时，用空白view作为tag之前的距离填充
					View view = new View(context);
					view.setLayoutParams(new LayoutParams(tagPadding, LayoutParams.MATCH_PARENT));
					layout.addView(view);
				}
				
			}
			mRootLayout.addView(layout);
		}
	}
	
	/**
	 * 选中状态
	 */
	private void showTagChecked(Context context, TextView textView){
		TagInfo tag = (TagInfo) textView.getTag();
		// 设置左边图片
		Drawable img = context.getResources().getDrawable(checkedImageIds[tag.getIndex()]);
		img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
		textView.setCompoundDrawables(img, null, null, null);
		textView.setCompoundDrawablePadding(22);
		textView.setLeft(39);
		// 设置文字颜色
		textView.setTextColor(Color.parseColor("#FFFFFF"));
		// 设置背景颜色,圆角形状等
		textView.setBackgroundResource(R.drawable.bg_tagview_checked);
	}
	
	/**
	 * 未选中状态
	 */
	private void showTagNormal(Context context, TextView textView){
		TagInfo tag = (TagInfo) textView.getTag();
		//设置左边图片
		Drawable img = context.getResources().getDrawable(normalImageIds[tag.getIndex()]);
		img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
		textView.setCompoundDrawables(img, null, null, null);
		textView.setCompoundDrawablePadding(22);
		textView.setLeft(39);
		// 设置文字颜色
		textView.setTextColor(Color.parseColor("#525252"));
		// 设置背景颜色,圆角形状等
		textView.setBackgroundResource(R.drawable.bg_tagview_normal);
	}
	
	private OnClickListener myTagCheckListener = new OnClickListener() {

        public void onClick(View v) {
        	TagInfo tag = (TagInfo) v.getTag();
        	tag.setChecked(!tag.isChecked());
        	if(tag.isChecked()){
        		//判断是否超过最大可选择标签数
        		if(getCheckedNumber() > getMaxCheckNumber()){
        			tag.setChecked(!tag.isChecked());  // 恢复当前tag的状态
        			mOverMaxNumberCheckListener.OnOverMaxNumber();
        			return;
        		}
        		
        		showTagChecked(getContext(), (TextView)v);
        	}else{
        		showTagNormal(getContext(), (TextView)v);
        	}
        	
        }

    };
    
    /** 获取选中的标签个数 */
    private int getCheckedNumber(){
    	int result = 0;
    	for(int i = 0; i < tags.size(); i ++){
    		if(tags.get(i).isChecked()){
    			result ++;
    		}
    	}
    	return result;
    }
    
    public void setOnOverMaxNumberCheckListener(OnOverMaxNumberCheckListener overMaxNumberCheckListene) {
    	mOverMaxNumberCheckListener = overMaxNumberCheckListene;
	}

}
